// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: fengyang

#pragma once

#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

#include "coin2/base/string_util.h"
#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/base/symbology/util.h"
#include "coin2/exchange/crypto/symbology/currency.h"

namespace coin2::exchange::crypto::symbology {

class CryptoProduct : public base::symbology::SpotProduct<CryptoCurrency, CryptoProduct>,
                       public base::symbology::ProductFromStrMixin<CryptoProduct> {
 public:
  typedef SpotProduct<CryptoCurrency, CryptoProduct> BaseProduct;

  CryptoProduct(const CryptoCurrency& base, const CryptoCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToCryptoNativeProduct(base, quote),
            ToCryptoNativeProduct(base, quote),
            base::market::ExchangeType::Crypto) {}

 public:
  static std::unique_ptr<CryptoProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<CryptoCurrency> base_ptr;
    std::unique_ptr<CryptoCurrency> quote_ptr;
    bool success =
        ParseCryptoNativeProduct(native_product, resolve_timestamp, &base_ptr, &quote_ptr);
    if (success) {
      return std::make_unique<CryptoProduct>(*base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParseCryptoNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<CryptoCurrency>* base_ptr,
      std::unique_ptr<CryptoCurrency>* quote_ptr) {
    
    std::vector<std::string> base_quote = Split(product_str, "_");
    CHECK_EQ(base_quote.size(), 2);

    *base_ptr = CryptoCurrency::FromNativeStrNoThrow(base_quote[0], resolve_timestamp);
    *quote_ptr = CryptoCurrency::FromNativeStrNoThrow(base_quote[1], resolve_timestamp);
    return true;
  }

  static std::string ToCryptoNativeProduct(
      const CryptoCurrency& base,
      const CryptoCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << "_" << quote.native_currency(MarketType::Spot);
    return ss.str();
  }
};

}  // namespace coin2::exchange::crypto::symbology
